package com.ruoyi.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.system.domain.PictureInfo;
import com.ruoyi.system.service.IPictureInfoService;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * 图片信息Controller
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/picture")
public class PictureInfoController extends BaseController
{
    private String prefix = "system/picture";

    @Autowired
    private IPictureInfoService pictureInfoService;

    /**
     * 跳转到图片标注页面
     */
    @GetMapping("/annotate")
    public String annotate()
    {
        return prefix + "/annotate";
    }

    /**
     * 跳转到标注历史页面
     */
    @GetMapping("/annotateHistoryPage")
    public String annotateHistory()
    {
        return prefix + "/annotateHistory";
    }

    /**
     * 跳转到历史记录列表页面
     */
    @GetMapping("/history")
    public String history()
    {
        return prefix + "/history";
    }

    /**
     * 跳转到历史记录详情页面
     */
    @GetMapping("/historyDetail/{id}")
    public String historyDetail(@PathVariable("id") Long id, ModelMap mmap)
    {
        mmap.put("pictureId", id);
        return prefix + "/historyDetail";
    }

    /**
     * 查询图片信息列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(PictureInfo pictureInfo)
    {
        startPage();
        List<PictureInfo> list = pictureInfoService.selectPictureInfoList(pictureInfo);
        return getDataTable(list);
    }

    /**
     * 获取下一张待标注的图片
     */
    @GetMapping("/getNext")
    @ResponseBody
    public AjaxResult getNextUnannotatedPicture()
    {
        PictureInfo picture = pictureInfoService.getNextUnannotatedPicture();
        if (picture == null)
        {
            return AjaxResult.error("图片已经标注完成");
        }
        return AjaxResult.success(picture);
    }

    /**
     * 保存标注信息并获取下一张图片
     */
    @Log(title = "图片标注", businessType = BusinessType.UPDATE)
    @PostMapping("/save")
    @ResponseBody
    public AjaxResult saveAnnotation(@RequestBody PictureInfo pictureInfo)
    {
        // 参数验证
        if (pictureInfo.getId() == 0)
        {
            return AjaxResult.error("图片ID不能为空");
        }
        if (pictureInfo.getRightFoot() == 0)
        {
            return AjaxResult.error("请选择右腿标签");
        }
        if (pictureInfo.getLeftFoot() == 0)
        {
            return AjaxResult.error("请选择左腿标签");
        }
        if (pictureInfo.getLeg() == 0)
        {
            return AjaxResult.error("请选择腿型标签");
        }

        try
        {
            PictureInfo nextPicture = pictureInfoService.saveAnnotationAndGetNext(pictureInfo);
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            
            if (nextPicture == null)
            {
                result.put("completed", true);
                result.put("message", "图片已经标注完成");
            }
            else
            {
                result.put("completed", false);
                result.put("nextPicture", nextPicture);
            }
            
            return AjaxResult.success(result);
        }
        catch (Exception e)
        {
            return AjaxResult.error("保存标注信息失败：" + e.getMessage());
        }
    }

    /**
     * 查询用户标注历史列表
     */
    @PostMapping("/annotationHistory")
    @ResponseBody
    public TableDataInfo annotationHistory(PictureInfo pictureInfo)
    {
        startPage();
        // 设置当前用户ID作为查询条件
        pictureInfo.setUpdateUserId(ShiroUtils.getSysUser().getUserId());
        List<PictureInfo> list = pictureInfoService.selectUserAnnotationHistory(pictureInfo);
        return getDataTable(list);
    }

    /**
     * 查询所有标注历史列表（管理员用）
     */
    @PostMapping("/allAnnotationHistory")
    @ResponseBody
    public TableDataInfo allAnnotationHistory(PictureInfo pictureInfo)
    {
        startPage();
        // 不设置用户ID，查询所有用户的标注历史
        List<PictureInfo> list = pictureInfoService.selectUserAnnotationHistory(pictureInfo);
        return getDataTable(list);
    }

    /**
     * 获取单条图片详情
     */
    @GetMapping("/{id}")
    @ResponseBody
    public AjaxResult getPictureDetail(@PathVariable("id") Long id)
    {
        PictureInfo picture = pictureInfoService.selectPictureInfoById(id);
        if (picture == null) {
            return AjaxResult.error("图片不存在");
        }
        return AjaxResult.success(picture);
    }
    
    /**
     * 获取上一张图片ID
     */
    @GetMapping("getPreviousId")
    @ResponseBody
    public AjaxResult getPreviousId(PictureInfo pictureInfo)
    {
        Long previousId = pictureInfoService.selectPreviousPictureId(pictureInfo);
        return AjaxResult.success(previousId);
    }
    
    /**
     * 获取下一张图片ID
     */
    @GetMapping("getNextId")
    @ResponseBody
    public AjaxResult getNextId(PictureInfo pictureInfo)
    {
        Long nextId = pictureInfoService.selectNextPictureId(pictureInfo);
        return AjaxResult.success(nextId);
    }

    /**
     * 更新标注信息
     */
    @Log(title = "标注历史", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    @ResponseBody
    public AjaxResult updateAnnotation(@RequestBody PictureInfo pictureInfo)
    {
        // 参数验证
        if (pictureInfo.getId() == null || pictureInfo.getId() == 0)
        {
            return AjaxResult.error("图片ID不能为空");
        }
        if (pictureInfo.getRightFoot() == null || pictureInfo.getRightFoot() == 0)
        {
            return AjaxResult.error("请选择右腿标签");
        }
        if (pictureInfo.getLeftFoot() == null || pictureInfo.getLeftFoot() == 0)
        {
            return AjaxResult.error("请选择左腿标签");
        }
        if (pictureInfo.getLeg() == null || pictureInfo.getLeg() == 0)
        {
            return AjaxResult.error("请选择腿型标签");
        }

        try
        {
            int result = pictureInfoService.updatePictureInfo(pictureInfo);
            return result > 0 ? AjaxResult.success() : AjaxResult.error("更新标注信息失败");
        }
        catch (Exception e)
        {
            return AjaxResult.error("更新标注信息失败：" + e.getMessage());
        }
    }

        @GetMapping("/reannotate/{id}")
    @ResponseBody
    public AjaxResult reannotate(@PathVariable("id") Long id)
    {
        PictureInfo picture = pictureInfoService.selectPictureInfoById(id);
        if (picture == null) {
            return AjaxResult.error("图片不存在");
        }
        // 验证是否是当前用户标注的
        if (!picture.getUpdateUserId().equals(ShiroUtils.getSysUser().getUserId())) {
            return AjaxResult.error("只能重新标注自己的图片");
        }
        return AjaxResult.success(picture);
    }
}